#include "stdafx.h"
#include "mystring.h"

allocator<char> mystring::alloc;

mystring::~mystring() {}

mystring::mystring(const char *s) {
	char *sl = const_cast<char*>(s);
	while (*sl) {
		++sl;
	}
	range_initializer(s, sl);
}

mystring::mystring(const mystring &s) {
	range_initializer(s.elements, s.end);
	cout << "copy constructor" << endl;
}

mystring& mystring::operator=(const mystring &rhs) {
	auto nd = alloc_n_copy(rhs.elements, rhs.end);
	free();
	elements = nd.first;
	end = nd.second;
	cout << "copy-assignment" << endl;
	return *this;
}


pair<char*, char*> mystring::alloc_n_copy(const char *b, const char *e) {
	auto newdata = alloc.allocate(e-b);
	return{ newdata,uninitialized_copy(b,e,newdata) };
}

void mystring::range_initializer(const char *b, const char *e) {
	auto data = alloc_n_copy(b, e);
	elements = data.first;
	end = data.second;
}

void mystring::free() {
	if (elements) {
		/*for (auto p = end; p != elements;) {
			alloc.destroy(--p);
		}*/
		for_each(elements, end, [this](char &c) {alloc.destroy(&c); });
		alloc.deallocate(elements, end - elements);
	}
}


